package cn.funeralobjects.util.converter;


import cn.funeralobjects.model.EnumNumberPair;
import cn.funeralobjects.util.EnumNumberUtils;

import javax.persistence.AttributeConverter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 基本的枚举 -> 数字的转换器
 *
 * @author FuneralObjects
 * Create date: 2020/4/15 6:59 AM
 */
public abstract class BaseEnumNumberConverter<E extends Enum<E>, N extends Number> implements AttributeConverter<E, N> {

    private Class<EnumNumberPair<E, N>> enumClass;

    @SuppressWarnings("unchecked")
    public BaseEnumNumberConverter() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        Type[] types = type.getActualTypeArguments();
        enumClass = (Class<EnumNumberPair<E, N>>) types[0];
        if (!EnumNumberPair.class.isAssignableFrom(enumClass)) {
            throw new IllegalArgumentException("The class[" + enumClass + "] must be extend EnumNumberPair.class!");
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public N convertToDatabaseColumn(E attribute) {
        EnumNumberPair<E, N> en = (EnumNumberPair<E, N>) attribute;
        return attribute == null ? null : en.getNumber();
    }

    @Override
    public E convertToEntityAttribute(N dbData) {
        return EnumNumberUtils.of(dbData, enumClass);
    }
}
